/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BusquedaReservas.java
 *
 * Created on 14-jun-2011, 21:20:33
 */
package guiBoleteria;

import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import logica.Fabrica;
import logica.IBoleteria;
import util.datatypes.DTReserva;
import util.exceptions.NoExisteClienteException;
import util.exceptions.NoExisteReservaException;

/**
 *
 * @author Administrador
 */
public class BusquedaReservas extends javax.swing.JFrame {

    public BusquedaReservas() {
        initComponents();
        jTable1.setModel(new ModeloBusquedaReserva());
        jTable1.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        PanelTitulo = new javax.swing.JPanel();
        lblBienvenida = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        PanelBusqueda = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        btnBuscar = new javax.swing.JButton();
        txtCedulaCliente = new javax.swing.JTextField();
        lblCedula = new javax.swing.JLabel();
        btnVer = new javax.swing.JButton();
        btnVenta = new javax.swing.JButton();
        PanelListado = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(800, 600));

        PanelTitulo.setBackground(new java.awt.Color(222, 222, 237));
        PanelTitulo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelTitulo.setLayout(new java.awt.BorderLayout());

        lblBienvenida.setBackground(new java.awt.Color(255, 255, 255));
        lblBienvenida.setFont(new java.awt.Font("Arial", 1, 24));
        lblBienvenida.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblBienvenida.setText("Búsqueda de Reservas");
        lblBienvenida.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblBienvenida.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        PanelTitulo.add(lblBienvenida, java.awt.BorderLayout.CENTER);

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/pequeñocinema.png"))); // NOI18N
        jLabel8.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelTitulo.add(jLabel8, java.awt.BorderLayout.LINE_START);

        getContentPane().add(PanelTitulo, java.awt.BorderLayout.NORTH);

        PanelBusqueda.setBackground(new java.awt.Color(192, 192, 213));
        PanelBusqueda.setFont(new java.awt.Font("Arial", 0, 11));
        PanelBusqueda.setMinimumSize(new java.awt.Dimension(10, 33));
        PanelBusqueda.setPreferredSize(new java.awt.Dimension(300, 246));
        PanelBusqueda.setLayout(new java.awt.BorderLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        txtCedulaCliente.setColumns(8);
        txtCedulaCliente.setFont(new java.awt.Font("Arial", 0, 11));
        txtCedulaCliente.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        txtCedulaCliente.setSelectedTextColor(new java.awt.Color(0, 0, 0));
        txtCedulaCliente.setSelectionColor(new java.awt.Color(255, 255, 255));
        txtCedulaCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCedulaClienteKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCedulaClienteKeyTyped(evt);
            }
        });

        lblCedula.setFont(new java.awt.Font("Arial", 0, 11));
        lblCedula.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblCedula.setText("Ingrese cédula: ");
        lblCedula.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);

        btnVer.setText("Ver detalles");
        btnVer.setEnabled(false);
        btnVer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerActionPerformed(evt);
            }
        });

        btnVenta.setText("Venta");
        btnVenta.setEnabled(false);
        btnVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVentaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCedula)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCedulaCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(47, 47, 47)
                .addComponent(btnBuscar)
                .addGap(26, 26, 26)
                .addComponent(btnVer)
                .addGap(18, 18, 18)
                .addComponent(btnVenta)
                .addContainerGap(50, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCedula)
                    .addComponent(btnBuscar)
                    .addComponent(txtCedulaCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnVer)
                    .addComponent(btnVenta))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        lblCedula.getAccessibleContext().setAccessibleParent(PanelBusqueda);

        PanelBusqueda.add(jPanel2, java.awt.BorderLayout.NORTH);

        PanelListado.setBackground(new java.awt.Color(208, 208, 219));
        PanelListado.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelListado.setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setFont(new java.awt.Font("Arial", 0, 11));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(35, 130));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 23;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 12;
        gridBagConstraints.ipady = 107;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        PanelListado.add(jScrollPane1, gridBagConstraints);

        PanelBusqueda.add(PanelListado, java.awt.BorderLayout.CENTER);
        PanelListado.getAccessibleContext().setAccessibleParent(PanelTitulo);

        getContentPane().add(PanelBusqueda, java.awt.BorderLayout.CENTER);
        PanelBusqueda.getAccessibleContext().setAccessibleParent(PanelTitulo);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        try
        {
            if (txtCedulaCliente.getText().length() > 0)
            {
                if (txtCedulaCliente.getText().length() == 8)
                {
                    jTable1.setVisible(true);
                    IBoleteria i = Fabrica.getIBoleteria();
                    int ci = Integer.parseInt(txtCedulaCliente.getText());
                    List<DTReserva> reservas = i.listarReservas(ci);
                    int reservasCanceladas = 0;
                    for(DTReserva r: reservas)
                    {
                        if(!r.isEstado() && !r.isVendida() && !i.chequearReservaEnHora(r))
                        {
                            i.cancelarReservaCliente(r, ci);
                            reservasCanceladas++;
                        }
                    }
                    if (reservasCanceladas > 0)
                    {
                        reservas.clear();
                        reservas = i.listarReservas(ci);
                    }
                    jTable1.setModel(new ModeloBusquedaReserva(reservas));
                    if (reservas.size() > 0)
                    {
                        btnVer.setEnabled(true);
                        btnVenta.setEnabled(true);
                    }
                    else
                    {
                        btnVer.setEnabled(false);
                        btnVenta.setEnabled(false);
                    }
                }
                else 
               JOptionPane.showMessageDialog(null, "La cédula tiene una cantidad incorrecta de caracteres", "Advertencia", JOptionPane.ERROR_MESSAGE);
            }
            else 
               JOptionPane.showMessageDialog(null, "Ingrese el número de cédula del cliente para obtener sus reservas", "Advertencia", JOptionPane.ERROR_MESSAGE); 
        } 
        catch(NoExisteReservaException ex)
        {
             JOptionPane.showMessageDialog(null, "No se encontro la reserva", "Error", JOptionPane.ERROR_MESSAGE);
        }
        catch (NoExisteClienteException ex) 
        {
            JOptionPane.showMessageDialog(null, "No se encontro el cliente", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void txtCedulaClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaClienteKeyPressed
    }//GEN-LAST:event_txtCedulaClienteKeyPressed

    private void btnVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerActionPerformed

        if (jTable1.getSelectedRow() >= 0)
        {
            int row = jTable1.getSelectedRow();

            try
            {
                IBoleteria i = Fabrica.getIBoleteria();

                int ci = Integer.parseInt(txtCedulaCliente.getText());

                List<DTReserva> reservas = i.listarReservas(ci);

                jTable1.setModel(new ModeloBusquedaReserva(reservas));

                DTReserva r = reservas.get(row);

                VerReserva frm = new VerReserva(r, ci);
                frm.setVisible(true);
             }
            catch (NoExisteClienteException ex) 
            {
                JOptionPane.showMessageDialog(null, "No se encontro el Cliente", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        else
           JOptionPane.showMessageDialog(null, "Seleccione un elemento de la lista", "Advertencia", JOptionPane.ERROR_MESSAGE); 
    }//GEN-LAST:event_btnVerActionPerformed

    private void txtCedulaClienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaClienteKeyTyped

        char c = evt.getKeyChar();

        if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))
        {
            getToolkit().beep();
            evt.consume();
        }
    }//GEN-LAST:event_txtCedulaClienteKeyTyped

    private void btnVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVentaActionPerformed

        if (jTable1.getSelectedRow() >= 0)
        {
            int row = jTable1.getSelectedRow();

            try
            {
                IBoleteria i = Fabrica.getIBoleteria();

                int ci = Integer.parseInt(txtCedulaCliente.getText());

                List<DTReserva> reservas = i.listarReservas(ci);

                jTable1.setModel(new ModeloBusquedaReserva(reservas));

                DTReserva r = reservas.get(row);

                if (r.isEstado())
                    JOptionPane.showMessageDialog(null, "La reserva fue cancelada", "Error", JOptionPane.ERROR_MESSAGE);

                else if (r.isVendida())
                    JOptionPane.showMessageDialog(null, "La reserva ya fue vendida", "Advertencia", JOptionPane.ERROR_MESSAGE);

                else if (!i.chequearReservaEnHora(r))
                {
                    JOptionPane.showMessageDialog(null, "La reserva paso su tiempo de actividad, 45 minutos, será cancelada", "Error", JOptionPane.ERROR_MESSAGE);
                    int result = i.cancelarReservaCliente(r, ci);
                }
                else
                {
                    GenerarEntrada frm = new GenerarEntrada(r);
                    frm.setVisible(true);
                }
             }
            catch (NoExisteClienteException ex) 
            {
                JOptionPane.showMessageDialog(null, "No se encontro el Cliente", "Error", JOptionPane.ERROR_MESSAGE);
            }
            catch (NoExisteReservaException ex)
            {
                JOptionPane.showMessageDialog(null, "No se encontro la reserva", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        else
           JOptionPane.showMessageDialog(null, "Seleccione un elemento de la lista", "Advertencia", JOptionPane.ERROR_MESSAGE);
    }//GEN-LAST:event_btnVentaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BusquedaReservas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelBusqueda;
    private javax.swing.JPanel PanelListado;
    private javax.swing.JPanel PanelTitulo;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnVenta;
    private javax.swing.JButton btnVer;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblBienvenida;
    private javax.swing.JLabel lblCedula;
    private javax.swing.JTextField txtCedulaCliente;
    // End of variables declaration//GEN-END:variables
}
